﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Services.Providers;
using DoveSiButta.Models;
using System.Web.Hosting;
using System.IO;
using System.Data.Services;
using System.Data.Objects;
using System.Diagnostics;


namespace DoveSiButta.Services
{
    public class DoveSiButtaStreamProvider : IDataServiceStreamProvider, IDisposable
    {

        private string imageFilePath;
        private Picture cachedEntity;
        private DoveSiButtaEntities context;

        private string tempFile = "temp";


        public DoveSiButtaStreamProvider(DoveSiButtaEntities context)
        {
            this.context = context;
            // Get the physical path to the app_data directory used to store the image files.
            imageFilePath = HostingEnvironment.MapPath("~/Pictures/"); //~/App_Data/
            
            //StreamWriter sw = new StreamWriter(imageFilePath + "/tutto.txt");
            //sw.WriteLine(imageFilePath);
            //sw.Close();

            try
            {
                // Create a temp file to store the new images during POST operations.
                //D:\Hosting\9292428\html
                //tempFile = @"\\WAGNER\wwwroot$\c0051d9bd.hostnd\htdocs\www\Pictures\pippo123.jpg"; // Path.GetTempFileName();
                string tempFileName = DateTime.Now.Ticks.ToString();
                tempFile = @"D:\Hosting\9292428\html\Pictures\" + tempFileName + ".jpg";
                FileStream fs = File.Create(tempFile);
                fs.Close();


            }
            catch { }
        }


        #region IDataServiceStreamProvider Members

        public void DeleteStream(object entity, DataServiceOperationContext operationContext)
        {
            Picture image = entity as Picture;
            if (image == null)
            {
                throw new DataServiceException(500, "Internal Server Error.");
            }

            try
            {
                // Delete the requested file by using the key value.
                File.Delete(imageFilePath + image.Picture_Filename.ToString());
            }
            catch (IOException ex)
            {
                throw new DataServiceException("The newBox could not be found.", ex);
            }
        }

        [HandleErrorWithELMAH]
        public Stream GetReadStream(object entity, string etag, bool?
            checkETagForEquality, DataServiceOperationContext operationContext)
        {
            if (checkETagForEquality != null)
            {
                // This stream provider implementation does not support 
                // ETag headers for media resources. This means that we do not track 
                // concurrency for a media resource and last-in wins on updates.
                throw new DataServiceException(400,
                    "This sample service does not support the ETag header for a media resource.");
            }

            Picture image = entity as Picture;
            if (image == null)
            {
                throw new DataServiceException(500, "Internal Server Error.");
            }

            // Build the full path to the stored image file, which includes the entity key.
            string fullImageFilePath = imageFilePath + image.Picture_Filename;

            if (!File.Exists(fullImageFilePath))
            {
                throw new DataServiceException(500, "The newBox could not be found.");
            }

            // Return a stream that contains the requested file.
            return new FileStream(fullImageFilePath, FileMode.Open);
        }

        public Uri GetReadStreamUri(object entity, DataServiceOperationContext operationContext)
        {
            // Allow the runtime set the URI of the Media Resource.
            return null;
        }

        public string GetStreamContentType(object entity, DataServiceOperationContext operationContext)
        {
            // Get the PhotoInfo entity instance.
            Picture image = entity as Picture;
            if (image == null)
            {
                throw new DataServiceException(500, "Internal Server Error.");
            }

            return "image/jpeg"; //image.Picture_Filename;
        }

        public string GetStreamETag(object entity, DataServiceOperationContext operationContext)
        {
            // This sample provider does not support the eTag header with media resources.
            // This means that we do not track concurrency for a media resource 
            // and last-in wins on updates.
            //return null;
            return string.Empty;
        }

        [HandleErrorWithELMAH]
        public Stream GetWriteStream(object entity, string etag, bool?
            checkETagForEquality, DataServiceOperationContext operationContext)
        {
            if (checkETagForEquality != null)
            {
                // This stream provider implementation does not support ETags associated with BLOBs.
                // This means that we do not track concurrency for a media resource 
                // and last-in wins on updates.
                throw new DataServiceException(400,
                    "This demo does not support ETags associated with BLOBs");
            }

            Picture newBox = entity as Picture;
            
            if (newBox == null)
            {
                throw new DataServiceException(500, "Internal Server Error: "
                + "the Media Link Entry could not be determined.");
            }

            // Handle the POST request.
            if (operationContext.RequestMethod == "POST")
            {
                // Set the file name from the Slug header; if we don't have a 
                // Slug header, just set a temporary name which is overwritten 
                // by the subsequent MERGE request from the client. 
                string format = "yyyyMMdd_hhmmss";
                DateTime time = DateTime.Now;
                newBox.Picture_Filename = time.ToString(format) + System.IO.Path.GetRandomFileName() + ".jpg";  //operationContext.RequestHeaders["Slug"] ?? "newFile";
                //hen using the Entity Framework provider, your implementation must set any required properties of this entity instance, which can be done either by using data from the slug message header or by setting default values
                //newBox.Address = ((Box)entity).Address;
                //newBox.BoxType = ((Box)entity).BoxType;
                //newBox.ContactPhone = ((Box)entity).ContactPhone;
                //newBox.Country = ((Box)entity).Country;
                //newBox.Description = ((Box)entity).Description;
                //newBox.EventDate = ((Box)entity).EventDate;
                //newBox.HostedBy = ((Box)entity).HostedBy;
                //newBox.Latitude = ((Box)entity).Latitude;
                //newBox.Longitude = ((Box)entity).Longitude;
                //newBox.Title = ((Box)entity).Title;
                newBox.LinkedBoxID = Convert.ToInt32(operationContext.RequestHeaders["Slug"]);
                // Set the required DateTime values.
                //image.EventDate= DateTime.Today;
                //image.DateAdded = DateTime.Today;

                // Set the content type, which cannot be null.
                //image.ContentType = operationContext.RequestHeaders["Content-Type"];

                // Cache the current entity to enable us to both create a key based storage file name 
                // and to maintain transactional integrity in the disposer; we do this only for a POST request.
                cachedEntity = newBox;

                return new FileStream(tempFile, FileMode.Open);
            }
            // Handle the PUT request
            else
            {
                // Return a stream to write to an existing file.
                return new FileStream(imageFilePath + newBox.Picture_Filename.ToString(),
                    FileMode.Open, FileAccess.Write);
            }
        }

        [HandleErrorWithELMAH]
        public string ResolveType(string entitySetName, DataServiceOperationContext operationContext)
        {
             //We should only be handling PhotoInfo types.
            if (entitySetName == "Picture")
            {
                return  "DoveSiButtaModel.Picture";
            }
            else
            {
                // This will raise an DataServiceException.
                return null;
            }
        }

        public int StreamBufferSize
        {
            // Use a buffer size of 64K bytes.
            get { return 32000; }
        }

        #endregion

        #region IDisposable Members

        [HandleErrorWithELMAH]
        public void Dispose()
        {
            // If we have a cached entity, it must be a POST request.
            if (cachedEntity != null)
            {
                // Get the new entity from the Entity Framework object state manager.
                ObjectStateEntry entry = this.context.ObjectStateManager.GetObjectStateEntry(cachedEntity);

                if (entry.State == System.Data.EntityState.Unchanged)
                {
                    //FOR DEBUG!!!
                    //StreamWriter sw = new StreamWriter(imageFilePath + "/tutto.txt",false);
                    //sw.WriteLine(cachedEntity.Picture_Filename.ToString());
                    //sw.Close();
                    //END DEBUG!!!

                    // Since the entity was created successfully, move the temp file into the 
                    // storage directory and rename the file based on the new entity key.
                    File.Move(tempFile, imageFilePath + cachedEntity.Picture_Filename.ToString());
                    
                    // Delete the temp file.
                    //File.Delete(tempFile);
                }
                else if (entry.State == System.Data.EntityState.Added)
                {

                    //context.AddObject("Boxes", cachedEntity);
                    //File.Move(tempFile, imageFilePath + cachedEntity.Picture_Filename.ToString());

                    //// Delete the temp file.
                    //File.Delete(tempFile);
                }
                else
                {
                    // A problem must have occurred when saving the entity to the database, 
                    // so we should delete the entity and temp file.
                    //context.DeleteObject(cachedEntity);
                    context.DeleteObject(cachedEntity);
                    //File.Delete(tempFile);

                    throw new DataServiceException("An error occurred. The photo could not be saved.");
                }
            }
            //else
            //{
            //    throw new DataServiceException("Sono qua");
            //}
        }

        #endregion
    }
}